function [X,varargout] = make_movie(path1,varargin)
% Makes a movie from a sequence of fluorescent images
% given a certain threshold to display fluorescence intensity
% Syntax
% [X,varargout] = make_movie(path1,varargin)
% Inputs:
% path1: Sequence path
% file: 'avi' -> movie 'tif' -> tiff images 'png' -> png images or 'none'
%        if equal to 'nodisp' no figure is displayed
% threshold: In percentage, usually set at 20%
% Outputs:
% X: Array ready for PCA
% k: Total of images
% t: cell containing acquisition time in seconds
% D: Bias (dark) image
% F: Fluorescent reference
% R_cell: Raw images
% I_cell: Corrected images
% photo: Photographic grayscale image
% EGC 2009/07/22

% Default values
file = 'none';  threshold = 0.2;
if ~isempty(varargin)
    file = varargin(1);
    if length(varargin)>1
        threshold = varargin{2};
    end
end

Dname = dir(path1);                         % Sequence folder
if ~strcmp(file,'nodisp')
%     figure; 
%     set (gcf,'color','white');
%     colormap gray;
h2 = figure;
set (h2,'color','white');
end

if strcmp(file,'avi')
    aviobj = avifile([path1 '\AEK20090415141520_SEQ.avi'],...
        'fps',2);                           % Create avi file
end

n = 1;                                      % Folder counter
for k = 1:length(Dname),
    if (Dname(k,1).isdir == 1) && ~(strcmp(Dname(k,1).name,'.') || strcmp(Dname(k,1).name,'..'))
        A{n,1} = Dname(k,1).name;               % Contains directory names
        n = n+1;
    end
end
path2 = [path1 '\' A{1,1}];
R = imread([path2 '\luminescent.TIF']);     % First Raw Image
photo = imread([path2 '\photograph.TIF']);  % Photo Image
photo = imresize(photo,size(R));
X = zeros([size(R,1)*size(R,2) length(A)]); % Preallocating Image sequence
t = zeros([1 length(A)]);                   % Preallocating time array
R_cell = cell(size(A));
I_cell = cell(size(A));
for k = 1:length(A),
	path2 = [path1 '\' A{k,1}];
    R = imread([path2 '\luminescent.TIF']); % Raw Image
    D = imread([path2 '\readbiasonly.TIF']);% Bias (Dark) Image
    F =  imread([path2...
        '\fluorescentreference.TIF']);      % Fluorescent reference
	I = double(R - D) ./ double(F - D);     % Background and flatfield correction
    M = F - D;
    M = mean(M(:));                         % Determine the average pixel value M in the corrected flat frame (F-D).
    I = M * I;                              % Corrected Image
    % Spatial filtering
    h = [1 2 1; 2 4 2; 1 2 1] / 16;         % Convolution kernel (filter)
    I = imfilter(I,h,'replicate');
% -------------------------------------------------------------------------
% Optional adjustment (don't use)
%     I = I ./ max(I(:));                     % Normalized to its own maximum
%     J = imadjust(L-B,...
%     stretchlim(L-B,[0.92 1]),[]);           % Adjusted Image
%     imagesc(J); colorbar;
% -------------------------------------------------------------------------        
    if ~strcmp(file,'nodisp')
%         imagesc(I); colorbar;
% -------------------------------------------------------------------------        
h1 = figure;
set(h1,'visible','off')                         % Invisible window
set (h1,'color','white');
Itempo = I ./ max(I(:));
Itempo = Itempo .* (Itempo>threshold);
imagesc(Itempo)
colormap hot
axis square
axis off
carte_orig = get(gcf,'Colormap');
carte = ind2rgb(gray2ind(Itempo),carte_orig);
close(h1)                                       % Close invisble window

imagesc(photo);
colormap gray
axis square
hold on
hax3 = imshow(carte);
gca;
set(hax3, 'AlphaData',Itempo>threshold);
% -------------------------------------------------------------------------

    end
    
    % Raw and corrected images saved in a cell
    R_cell{k,1} = R;
    I_cell{k,1} = I;
    
    X(:,k) = I(:);                          % Forming sequence
    texto = textread([path2 '\AnalyzedClickInfo.txt'],...
            '%s', 'delimiter', '\n', 'whitespace', '');
    if(k==1)
        texto{21,1}(18) = ' ';              % Replace tab by a space
        txt = regexp(texto{22,1},'\d');     % Acquisition seconds
        t(k) = str2double(texto{22,1}(txt));
        if ~strcmp(file,'nodisp')
            title(sprintf(texto{21,1}));        % Acquisition time info
        end
    else
        texto{22,1}(18) = ' ';              % Replace tab by a space
        txt = regexp(texto{23,1},'\d');     % Acquisition seconds
        t(k) = str2double(texto{23,1}(txt));
        if ~strcmp(file,'nodisp')
            title(sprintf(texto{22,1}));        % Acquisition time info
        end
    end
    if strcmp(file,'avi')
        frame = getframe(gcf);               % Grabs a full frame
        aviobj = addframe(aviobj,frame);    % Adds frame to avi file
        cla                                 % Clears axes
    end
    if strcmp(file,'png')
        export_fig([path1 '\' sprintf('%06.0f',k)],'-png',gcf)
    end
    if strcmp(file,'tif')
        export_fig([path1 '\' sprintf('%06.0f',k)],'-tif',gcf)
    end
    if ~strcmp(file,'nodisp')
        pause(0.01)
    end
end
t = t - t(1);                               % Start at t = 0 sec
if strcmp(file,'avi')
    aviobj = close(aviobj);                 % Closes avi file
end
nout = max(nargout,1)-1;
for m = 1:nout,
    switch(m)
    case 1
        varargout(1) = {k};
    case 2
        varargout(2) = {t};
    case 3
        varargout(3) = {D};
    case 4
        varargout(4) = {F};
    case 5
        varargout(5) = {R_cell};
    case 6
        varargout(6) = {I_cell};
    case 7
        varargout(7) = {photo};
    end
end
% X = X ./ max(X(:));                       % Normalize to its own maximum
                                            % (not used)